// 书签管理系统 - 数据存储模块
class BookmarkStorage {
    constructor() {
        this.storageKey = 'bookmarks_data';
        this.categoriesKey = 'bookmark_categories';
        this.init();
    }

    // 初始化存储
    init() {
        if (!this.getData()) {
            this.saveData({
                bookmarks: [],
                categories: [
                    { id: 'default', name: '默认', color: '#007bff' },
                    { id: 'work', name: '工作', color: '#28a745' },
                    { id: 'study', name: '学习', color: '#6f42c1' },
                    { id: 'tools', name: '工具', color: '#fd7e14' }
                ],
                nextId: 1
            });
        }
    }

    // 获取所有数据
    getData() {
        try {
            const data = localStorage.getItem(this.storageKey);
            return data ? JSON.parse(data) : null;
        } catch (error) {
            console.error('Error loading data from localStorage:', error);
            return null;
        }
    }

    // 保存所有数据
    saveData(data) {
        try {
            localStorage.setItem(this.storageKey, JSON.stringify(data));
            return true;
        } catch (error) {
            console.error('Error saving data to localStorage:', error);
            return false;
        }
    }

    // 获取所有书签
    getBookmarks() {
        const data = this.getData();
        return data ? data.bookmarks : [];
    }

    // 获取所有分类
    getCategories() {
        const data = this.getData();
        return data ? data.categories : [];
    }

    // 添加书签
    addBookmark(bookmark) {
        const data = this.getData();
        if (!data) return false;

        const newBookmark = {
            id: data.nextId++,
            name: bookmark.name,
            url: bookmark.url,
            notes: bookmark.notes || '',
            sort: bookmark.sort || 0,
            category: bookmark.category || '',
            created: new Date().toISOString(),
            updated: new Date().toISOString()
        };

        data.bookmarks.push(newBookmark);
        return this.saveData(data) ? newBookmark : false;
    }

    // 更新书签
    updateBookmark(id, updates) {
        const data = this.getData();
        if (!data) return false;

        const bookmarkIndex = data.bookmarks.findIndex(b => b.id === id);
        if (bookmarkIndex === -1) return false;

        data.bookmarks[bookmarkIndex] = {
            ...data.bookmarks[bookmarkIndex],
            ...updates,
            updated: new Date().toISOString()
        };

        return this.saveData(data) ? data.bookmarks[bookmarkIndex] : false;
    }

    // 删除书签
    deleteBookmark(id) {
        const data = this.getData();
        if (!data) return false;

        const bookmarkIndex = data.bookmarks.findIndex(b => b.id === id);
        if (bookmarkIndex === -1) return false;

        data.bookmarks.splice(bookmarkIndex, 1);
        return this.saveData(data);
    }

    // 获取单个书签
    getBookmark(id) {
        const bookmarks = this.getBookmarks();
        return bookmarks.find(b => b.id === id) || null;
    }

    // 按分类获取书签
    getBookmarksByCategory(categoryId) {
        const bookmarks = this.getBookmarks();
        if (!categoryId) return bookmarks;
        return bookmarks.filter(b => b.category === categoryId);
    }

    // 搜索书签
    searchBookmarks(query) {
        const bookmarks = this.getBookmarks();
        if (!query) return bookmarks;

        const searchTerm = query.toLowerCase();
        return bookmarks.filter(bookmark => 
            bookmark.name.toLowerCase().includes(searchTerm) ||
            bookmark.url.toLowerCase().includes(searchTerm) ||
            bookmark.notes.toLowerCase().includes(searchTerm)
        );
    }

    // 添加分类
    addCategory(category) {
        const data = this.getData();
        if (!data) return false;

        // 检查分类名是否已存在
        if (data.categories.some(c => c.name === category.name)) {
            return false;
        }

        const newCategory = {
            id: category.name.toLowerCase().replace(/\s+/g, '_'),
            name: category.name,
            color: category.color || '#007bff'
        };

        data.categories.push(newCategory);
        return this.saveData(data) ? newCategory : false;
    }

    // 删除分类
    deleteCategory(categoryId) {
        const data = this.getData();
        if (!data) return false;

        // 不能删除默认分类
        if (categoryId === 'default') return false;

        // 移除分类
        const categoryIndex = data.categories.findIndex(c => c.id === categoryId);
        if (categoryIndex === -1) return false;

        data.categories.splice(categoryIndex, 1);

        // 将该分类下的书签移到默认分类
        data.bookmarks.forEach(bookmark => {
            if (bookmark.category === categoryId) {
                bookmark.category = '';
            }
        });

        return this.saveData(data);
    }

    // 获取分类统计
    getCategoryStats() {
        const bookmarks = this.getBookmarks();
        const categories = this.getCategories();
        const stats = {};

        // 初始化统计
        categories.forEach(category => {
            stats[category.id] = 0;
        });
        stats[''] = 0; // 未分类

        // 统计每个分类的书签数量
        bookmarks.forEach(bookmark => {
            const categoryId = bookmark.category || '';
            if (stats.hasOwnProperty(categoryId)) {
                stats[categoryId]++;
            } else {
                stats['']++;
            }
        });

        return stats;
    }

    // 排序书签
    sortBookmarks(bookmarks, sortBy = 'sort') {
        return [...bookmarks].sort((a, b) => {
            switch (sortBy) {
                case 'name':
                    return a.name.localeCompare(b.name);
                case 'created':
                    return new Date(b.created) - new Date(a.created);
                case 'updated':
                    return new Date(b.updated) - new Date(a.updated);
                case 'sort':
                default:
                    // 先按排序号，再按创建时间
                    if (a.sort !== b.sort) {
                        return a.sort - b.sort;
                    }
                    return new Date(a.created) - new Date(b.created);
            }
        });
    }

    // 导出数据
    exportData() {
        const data = this.getData();
        if (!data) return null;

        const exportData = {
            ...data,
            exportDate: new Date().toISOString(),
            version: '1.0'
        };

        return JSON.stringify(exportData, null, 2);
    }

    // 导入数据
    importData(jsonString) {
        try {
            const importData = JSON.parse(jsonString);
            
            // 验证数据结构
            if (!importData.bookmarks || !Array.isArray(importData.bookmarks)) {
                throw new Error('无效的书签数据格式');
            }
            
            if (!importData.categories || !Array.isArray(importData.categories)) {
                throw new Error('无效的分类数据格式');
            }

            // 合并数据
            const currentData = this.getData() || { bookmarks: [], categories: [], nextId: 1 };
            
            // 合并分类（避免重复）
            const existingCategoryNames = currentData.categories.map(c => c.name);
            const newCategories = importData.categories.filter(c => 
                !existingCategoryNames.includes(c.name)
            );
            
            // 合并书签
            const maxId = Math.max(
                ...currentData.bookmarks.map(b => b.id),
                currentData.nextId - 1,
                0
            );
            
            const newBookmarks = importData.bookmarks.map((bookmark, index) => ({
                ...bookmark,
                id: maxId + index + 1,
                imported: new Date().toISOString()
            }));

            const mergedData = {
                bookmarks: [...currentData.bookmarks, ...newBookmarks],
                categories: [...currentData.categories, ...newCategories],
                nextId: maxId + importData.bookmarks.length + 1
            };

            return this.saveData(mergedData) ? {
                success: true,
                imported: {
                    bookmarks: newBookmarks.length,
                    categories: newCategories.length
                }
            } : { success: false, error: '保存数据失败' };

        } catch (error) {
            return { success: false, error: error.message };
        }
    }

    // 清空所有数据
    clearAllData() {
        localStorage.removeItem(this.storageKey);
        this.init();
        return true;
    }

    // 备份数据到文件
    backupToFile() {
        const data = this.exportData();
        if (!data) return false;

        const blob = new Blob([data], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        
        a.href = url;
        a.download = `bookmarks_backup_${new Date().toISOString().split('T')[0]}.json`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        
        return true;
    }

    // 数据验证
    validateBookmark(bookmark) {
        const errors = [];

        if (!bookmark.name || bookmark.name.trim() === '') {
            errors.push('书签名称不能为空');
        }

        if (!bookmark.url || bookmark.url.trim() === '') {
            errors.push('书签地址不能为空');
        } else {
            try {
                new URL(bookmark.url);
            } catch {
                errors.push('请输入有效的网址');
            }
        }

        if (bookmark.sort !== undefined && (isNaN(bookmark.sort) || bookmark.sort < 0)) {
            errors.push('排序必须是大于等于0的数字');
        }

        return {
            valid: errors.length === 0,
            errors
        };
    }

    // 获取数据统计信息
    getStats() {
        const data = this.getData();
        if (!data) return null;

        const categoryStats = this.getCategoryStats();
        const totalBookmarks = data.bookmarks.length;
        const totalCategories = data.categories.length;
        
        return {
            totalBookmarks,
            totalCategories,
            categoryStats,
            lastModified: data.bookmarks.length > 0 ? 
                Math.max(...data.bookmarks.map(b => new Date(b.updated || b.created))) : null
        };
    }
}